package com.pesilo.mvc.model
{
	import com.pesilo.mvc.controller.ApplicationFacade;
	import com.pesilo.mvc.model.vo.DataParamVO;
	import com.pesilo.net.http.HttpService;
	import com.pesilo.norms.Api;
	import com.pesilo.norms.GetUnicode;
	import com.pesilo.norms.Weather;
	
	import flash.net.URLRequestMethod;
	
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;

	public class WeatherDataProxy extends Proxy
	{
		public static const NAME:String="WeatherDataProxy";
		public function WeatherDataProxy()
		{
			super(NAME);
		}
		
		public function getWeatherData():void{
			var ipVO:DataParamVO=new DataParamVO(Api.API_GET_IP_URL,getIP);
			HttpService.getInstance().getData(null,ipVO,true);
		}
		
		private function getIP(data:Object):void{
			var ip:String=data["ip"];
			
			var addressVO:DataParamVO=new DataParamVO(Api.API_GET_ADDRESS_URL,getAddress,{"myip":ip});
			addressVO.method=URLRequestMethod.GET;
			HttpService.getInstance().getData(null,addressVO,true);
		}
		
		private function getAddress(data:Object):void{
			var city:String=data["city"];
			
			var p:String;//省份
			var t:String;//城市
			
			var a:int=city.indexOf("省");
			var b:int=city.indexOf("市");
			if(a==-1&&b!=-1){
				t=city.substring(0,b);
			}else if(b==-1&&a!=-1){
				if(city.length-1>a){
					p=city.substring(0,a);
					t=city.substring(a+1,city.length);
				}else{
					p=city.substring(0,a);
				}
			}else{
				p=city.substring(0,a);
				t=city.substring(a+1,b);
			}
			
			p=GetUnicode.toPinyin(p);
			
			var weatherVO:DataParamVO=new DataParamVO(Api.API_GET_WEATHER_URL,getWeather,{"p":p,"t":t});
			weatherVO.method=URLRequestMethod.GET;
			HttpService.getInstance().getData(null,weatherVO,true);
		}
		
		private function getWeather(data:Object):void{
			var weather:String=data["weather"];
			//检测天气
			trace("The weather is "+weather+"!");
			var w:String;
			if(weather.indexOf(Weather.SNOW)!=-1){
				w=Weather.SNOW;
			}else if(weather.indexOf(Weather.RAIN)!=-1){
				w=Weather.RAIN;
			}else if(weather.indexOf(Weather.CLOUD)!=-1){
				w=Weather.CLOUD;
			}else if(weather.indexOf(Weather.SUN)!=-1){
				w=Weather.SUN;
			}
			
			facade.sendNotification(ApplicationFacade.SET_WEATHER_EVENT,w);
		}
	}
}